/**
 * Summary: js脚本所能执行的函数空间
 * Version 1.0
 * Date: 13-11-20
 * Time: 下午4:40
 * Copyright: Copyright (c) 2013
 */

package cn.pedant.SafeWebViewBridge.sample;

import cn.pedant.SafeWebViewBridge.JsCallback;
import cn.pedant.SafeWebViewBridge.ResourceTable;
import cn.pedant.SafeWebViewBridge.sample.util.TaskExecutor;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.system.version.SystemVersion;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

//HostJsScope中需要被JS调用的函数，必须定义成public static，且必须包含WebView这个参数
public class HostJsScope {
    private static final int NUM_15 = 15;
    private static final int NUM_60 = 60;
    private static final int NUM_65 = 65;
    private static final int NUM_120 = 120;
    private static final int NUM_200 = 200;
    private static final int NUM_1000 = 1000;

    /**
     * 短暂气泡提醒
     *
     * @param webView 浏览器
     * @param message 提示信息
     */
    public static void toast(WebView webView, String message) {
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(webView.getContext())
                .parse(ResourceTable.Layout_toast_layout, null, false);
        ((Text) layout.findComponentById(ResourceTable.Id_message)).setText(message);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(NUM_200, NUM_200, NUM_200, NUM_200));
        shapeElement.setCornerRadius(NUM_60);
        layout.setBackground(shapeElement);
        layout.setMarginBottom(NUM_120);
        new ToastDialog(webView.getContext())
                .setComponent(layout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.BOTTOM)
                .setTransparent(true)
                .show();
    }

    /**
     * 可选择时间长短的气泡提醒
     *
     * @param webView 浏览器
     * @param message 提示信息
     * @param isShowLong 提醒时间方式
     */
    public static void toast(WebView webView, String message, int isShowLong) {
        new ToastDialog(webView.getContext()).setText(message).setDuration(isShowLong).show();
    }

    /**
     * 弹出记录的测试JS层到Java层代码执行损耗时间差
     *
     * @param webView 浏览器
     * @param timeStamp js层执行时的时间戳
     */
    public static void testLossTime(WebView webView, long timeStamp) {
        timeStamp = System.currentTimeMillis() - timeStamp;
        alert(webView, String.valueOf(timeStamp));
    }

    /**
     * 系统弹出提示框
     *
     * @param webView 浏览器
     * @param msg 信息
     */
    public static void alert(WebView webView, int msg) {
        alert(webView, String.valueOf(msg));
    }

    /**
     * 系统弹出提示框
     *
     * @param webView 浏览器
     * @param isMsg 信息
     */
    public static void alert(WebView webView, boolean isMsg) {
        alert(webView, String.valueOf(isMsg));
    }

    /**
     * 系统弹出提示框
     *
     * @param webView 浏览器
     * @param message 提示信息
     */
    public static void alert(WebView webView, String message) {
        CommonDialog builder = new CommonDialog(webView.getContext());
        builder.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        builder.setTransparent(true);

        Component component = LayoutScatter.getInstance(webView.getContext()).parse(ResourceTable.Layout_dialog_layout, null, false);
        setShapeElement(component);

        ((Text) component.findComponentById(ResourceTable.Id_title)).setText(webView.getContext().getString(ResourceTable.String_dialog_title_system_msg));
        ((Text) component.findComponentById(ResourceTable.Id_context)).setText(message);
        component.findComponentById(ResourceTable.Id_sure).setClickedListener(component1 -> builder.destroy());

        component.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        component.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
        builder.setContentCustomComponent(component);

        builder.show();
    }

    private static void setShapeElement(Component component) {
        component.setMarginRight(NUM_60);
        component.setMarginLeft(NUM_60);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setCornerRadius(NUM_15);
        shapeElement.setRgbColor(new RgbColor(NUM_65, NUM_65, NUM_65));
        component.setBackground(shapeElement);
    }

    /**
     * 获取设备IMSI
     *
     * @param webView 浏览器
     * @return 设备IMSI
     */
    public static String getIMSI(WebView webView) {
        /**
         * return ((TelephonyManager) webView.getContext().getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
         */
        return "暂时无法获取设备IMSI";
    }

    /**
     * 获取用户系统版本大小
     *
     * @param webView 浏览器
     * @return 安卓SDK版本
     */
    public static int getOsSdk(WebView webView) {
        return SystemVersion.getApiVersion();
    }

    //---------------- 界面切换类 ------------------

    /**
     * 结束当前窗口
     *
     * @param view 浏览器
     */
    public static void goBack(WebView view) {
        if (view.getContext() instanceof AbilitySlice) {
            view.getContext().stopAbility(((AbilitySlice) view.getContext()).getAbility().getIntent());
        }
    }

    /**
     * 传入Json对象
     *
     * @param view 浏览器
     * @param jo 传入的JSON对象
     * @return 返回对象的第一个键值对
     */
    public static String passJson2Java(WebView view, JsonObject jo) {
        Set<Map.Entry<String, JsonElement>> entries = jo.entrySet();
        String res = null;
        for (Map.Entry<String, JsonElement> entry : entries) {
            res = entry.getKey() + ":" + entry.getValue().getAsString();
            break;
        }
        return res;
    }

    /**
     * 将传入Json对象直接返回
     *
     * @param view 浏览器
     * @param jo 传入的JSON对象
     * @return 返回对象的第一个键值对
     */
    public static JsonObject retBackPassJson(WebView view, JsonObject jo) {
        return jo;
    }

    /**
     * overloadMethod
     *
     * @param view 浏览器
     * @param val cal
     * @return int
     */
    public static int overloadMethod(WebView view, int val) {
        return val;
    }

    /**
     * overloadMethod
     *
     * @param view 浏览器
     * @param val val
     * @return string
     */
    public static String overloadMethod(WebView view, String val) {
        return val;
    }

    public static class RetJavaObj {
        int intField;
        String strField;
        boolean isBoolField;

        public int getIntField() {
            return intField;
        }

        public void setIntField(int intField) {
            this.intField = intField;
        }

        public String getStrField() {
            return strField;
        }

        public void setStrField(String strField) {
            this.strField = strField;
        }

        public boolean isBoolField() {
            return isBoolField;
        }

        public void setBoolField(boolean boolField) {
            isBoolField = boolField;
        }
    }

    /**
     * retJavaObject
     *
     * @param view 浏览器
     * @return 集合
     */
    public static List<RetJavaObj> retJavaObject(WebView view) {
        RetJavaObj obj = new RetJavaObj();
        obj.setIntField(1);
        obj.setStrField("mine str");
        obj.setBoolField(true);
        List<RetJavaObj> rets = new ArrayList<RetJavaObj>();
        rets.add(obj);
        return rets;
    }

    /**
     * delayJsCallBack
     *
     * @param view 浏览器
     * @param ms 信息
     * @param backMsg 信息
     * @param jsCallback 回调
     */
    public static void delayJsCallBack(WebView view, int ms, final String backMsg, final JsCallback jsCallback) {
        TaskExecutor.scheduleTaskOnUiThread(ms * NUM_1000, new Runnable() {
            @Override
            public void run() {
                try {
                    jsCallback.apply(backMsg);
                } catch (JsCallback.JsCallbackException je) {
                    je.printStackTrace();
                }
            }
        });
    }

    /**
     * passLongType
     *
     * @param view 浏览器
     * @param ii ii
     * @return long
     */
    public static long passLongType(WebView view, long ii) {
        return ii;
    }
}